import * as THREE from "three";
import CameraControls from "camera-controls";
import { sceneOption as opts } from "../state";

export class CameraControl {
  public instance: CameraControls;

  constructor() {
    // 相机控制安装
    CameraControls.install({ THREE: THREE });

    this.instance = new CameraControls(opts.camera, opts.dom);
    this.instance.azimuthRotateSpeed = 1; // negative value to invert rotation direction
    this.instance.polarRotateSpeed = 1; // negative value to invert rotation direction
    this.instance.truckSpeed = 1;
    // instance.mouseButtons.wheel = CameraControls.ACTION.ZOOM;
    // instance.touches.two = CameraControls.ACTION.TOUCH_ZOOM_TRUCK;
    this.instance.saveState();
    let that = this;
    (function anim() {
      const delta = opts.clock.getDelta();
      const elapsed = opts.clock.getElapsedTime();
      const updated = that.instance.update(delta);

      // if ( elapsed > 30 ) { return; }

      requestAnimationFrame(anim);

      if (updated) {
        opts.renderer.render(opts.scene, opts.camera);
      }
    })();

    // this.disableMouseClickEvent();
    this.enableMouseMoveEvent();
    this.enableKeyboardEvent();
  }

  /**
   * 禁用鼠标事件
   */
  private disableMouseClickEvent(): void {
    this.instance.mouseButtons.left = CameraControls.ACTION.NONE;
    this.instance.mouseButtons.wheel = CameraControls.ACTION.NONE;
    this.instance.mouseButtons.middle = CameraControls.ACTION.NONE;
    this.instance.mouseButtons.right = CameraControls.ACTION.NONE;
  }

  /**
   * 开启移动监控
   */
  private enableMouseMoveEvent(): void {
    var onMouseMove = function (event) {
      var movementX =
        event.movementX || event.mozMovementX || event.webkitMovementX || 0;
      var movementY =
        event.movementY || event.mozMovementY || event.webkitMovementY || 0;

      let azimuthAngle = -movementX * 0.002;
      let polarAngle = -movementY * 0.002;
      opts.cameraControl.rotate(azimuthAngle, polarAngle, true);
    };
    opts.dom.addEventListener("mousemove", onMouseMove, false);
  }

  private enableKeyboardEvent(): void {
    document.onkeydown = function(event) {
      if(event.code === "Space"){
        opts.cameraControl.truck(0, -2, true);
        setTimeout(() => {
          opts.cameraControl.truck(0, 2, true);
        }, 500)
      }
    }
  }
}
